package com.quyunshuo.module.home.activity.stat

import androidx.lifecycle.viewModelScope
import com.github.mikephil.charting.data.BarEntry
import com.quyunshuo.edwinpro.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.activity.result.ResultRepository
import com.quyunshuo.module.home.activity.stat.chart.DateUtils
import com.quyunshuo.module.home.activity.stat.chart.WeeklySummary
import com.quyunshuo.module.home.room.entity.ConcentrationEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class StatViewModel @Inject constructor(private val mRepository: StatRepository) : BaseViewModel() {

    private val _stats = MutableStateFlow<StatsResult?>(null)
    val stats = _stats.asStateFlow()
    init{
        // 默认加载当前周的数据
        val (startDate, endDate) = DateUtils.getCurrentWeekRange()
        loadWeeklyDetails(startDate, endDate)
    }

    fun loadStats() {
        viewModelScope.launch(Dispatchers.IO) {
            _stats.value = try {
                // 获取三种统计数据
                val (days, minutes, count) = mRepository.getConcentrationStats()
                StatsResult.Success(days, minutes, count)
            } catch (e: Exception) {
                StatsResult.Error(e)
            }
        }
    }

    // 保存当前选中周的详细数据
    private val _weeklyDetails = MutableStateFlow<List<ConcentrationEntity>>(emptyList())
    val weeklyDetails = _weeklyDetails.asStateFlow()
    // 保存周统计数据
    val weeklySummary = MutableStateFlow<List<WeeklySummary>>(emptyList())

    // 保存周统计数据
    // 加载指定周的详细数据
    fun loadWeeklyDetails(startDate: String, endDate: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val details = mRepository.getWeeklyDetails(startDate, endDate)
            _weeklyDetails.emit(details)
        }
    }
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

    // 获取柱状图数据
    fun getChartDataForWeek(): ArrayList<BarEntry> {
        val details = weeklyDetails.value
        val entries = ArrayList<BarEntry>()

        // 创建周日到周六的位置映射
        val dayMap = mutableMapOf<String, Int>()
        val days = listOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
        days.forEachIndexed { index, day -> dayMap[day] = index }

        // 按天汇总数据
        val dailyTotals = DoubleArray(7) { 0.0 }
        details.forEach { entity ->
            // 获取星期几
            val date = dateFormat.parse(entity.focusDate) ?: return@forEach
            val cal = Calendar.getInstance().apply { time = date }
            val dayOfWeek = (cal.get(Calendar.DAY_OF_WEEK) + 5) % 7 // 转换为周一=0
            dailyTotals[dayOfWeek] =1.0
        }

        // 转换为图表条目
        dailyTotals.forEachIndexed { index, minutes ->
            entries.add(BarEntry(index.toFloat(), minutes.toFloat()))
        }

        return entries
    }

    // 结果密封类
    sealed class StatsResult {
        data class Success(val focusDays: Int, val totalMinutes: Int, val recordsCount: Int) : StatsResult()
        data class Error(val exception: Exception) : StatsResult()
    }
}
